import {createRouter ,createRouterMatcher,createWebHistory} from 'vue-router';
import { FormatToken,SettingUserRouter,Vaild} from '../tools';
import store from '../store'
import { ElMessage } from 'element-plus'

const router =createRouter({
    history:createWebHistory(),
    routes:[
        {
            name:"login",
            path:'/login',
            component:()=>import('../views/index/LoginPage.vue')
        },
        {
            name:"notfound",
            path:"/:pathMatch(.*)",
            component:()=>import('../views/index/NotFound.vue')
        },
        // {
        //     name:"user",
        //     path:"/user",
        //     component:()=>import('../views/admin/user/user.vue')
        // },
        // {
        //     name:"role",
        //     path:"/role",
        //     component:()=>import('../views/admin/role/role.vue')
        // },
        // {
        //     name:"menu",
        //     path:"/menu",
        //     component:()=>import('../views/admin/menu/menu.vue')
        // },
        
        {
            name:"admin",
            path:"/admin",
            component:()=>import('../views/index/AdminPage.vue'),
            children:[
                {
                    name:"desktop",
                    path:"/desktop",
                    component:()=>import('../views/index/Desktop.vue')
                },
                {
                    name:"person",
                    path:"/person",
                    component:()=>import('../views/index/PersonPage.vue')
                }
            ]

        },
    ]
})
router.beforeEach(async (to, from, next) => {
    if (store().Token == "" || !store().Token) {
        if (to.path != "/login" && to.path != "/") {
            next("/login")
        }
    } else {
        // 判断登录有效期，并且避免无限重定向
        if (!Vaild(FormatToken(store().Token)?.exp as number) && to.path != "/login") {
            ElMessage.warning("登录已过有效期，请重新登录！")
            next("/login")
        }
    }

    if (to.path != "/login") {
        await SettingUserRouter()
    }

    // 由于统一配置了404页面的原因，这里要判断一下当前是否已经进入404页面
    if (to.name == "notfound") {
        // 由于是在导航里动态添加的路由，刷新页面时无法读取（刷新页面时没有跳转所以没有触发导航机制）
        // 所以要进行手动跳转到动态添加的路由，但是前提是跳转的path在路由中存在才行
        if (router.getRoutes().find(p => p.path == to.path)) {
            // 经过一些列判断后没问题则跳转
            next(to.path)
            return;
        }
    }
    next()
})


export default router